// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: linchuan

#include "coin2/exchange/okex/api_order/native_rest_async_asio_subscriber.h"

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

#include "coin2/base/log.h"

namespace coin2::exchange::okex::api_order {

void OkexRestAsyncAsioSubscriber::QueryBalance() {
  auto http_context = rest_client()->QueryAccountInfo();
  http_context->handler =
      std::bind(&OkexRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void OkexRestAsyncAsioSubscriber::QueryOpenOrders(const std::string& native_symbol) {
  auto http_context =
      rest_client()->QueryOrders(native_symbol, static_cast<int32_t>(OrderStatus::OPEN));
  http_context->handler =
      std::bind(&OkexRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void OkexRestAsyncAsioSubscriber::QueryFinishedOrders(const std::string& native_symbol) {
  auto http_context =
      rest_client()->QueryOrders(native_symbol, static_cast<int32_t>(OrderStatus::DONE));
  http_context->handler =
      std::bind(&OkexRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void OkexRestAsyncAsioSubscriber::QueryFills(const std::string& native_symbol) {
  auto http_context = rest_client()->QueryFills(native_symbol, 100);
  http_context->handler =
      std::bind(&OkexRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void OkexRestAsyncAsioSubscriber::QueryTransfer() {
  auto http_context = rest_client()->QueryTransfer("BTC", "");
  if (!http_context) return;
  http_context->handler =
      std::bind(&OkexRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void OkexRestAsyncAsioSubscriber::SubscribeAsync() {
  AddPeriodicTask(
      std::bind(&OkexRestAsyncAsioSubscriber::QueryBalance, this),
      config_.query_account_balance_period_sec(),
      "query_balance");

  auto symbol_list = native_symbols();

  AddPeriodicTask(
      std::bind(&OkexRestAsyncAsioSubscriber::QueryOpenOrders, this, std::placeholders::_1),
      config_.query_open_orders_period_sec(),
      "query_open_orders",
      symbol_list);

  AddPeriodicTask(
      std::bind(&OkexRestAsyncAsioSubscriber::QueryFinishedOrders, this, std::placeholders::_1),
      config_.query_cancel_orders_period_sec(),
      "query_finished_orders",
      symbol_list);

  AddPeriodicTask(
      std::bind(&OkexRestAsyncAsioSubscriber::QueryFills, this, std::placeholders::_1),
      config_.query_fill_period_sec(),
      "query_fills",
      symbol_list);
}

}  // namespace coin2::exchange::okex::api_order
